const { query } = require('../../helper/db');
const { ok, door } = require('../../helper/util');

/**
 * @apiDefine ErrorResponse
 * @apiError (请求错误) {String} err_message 错误信息描述
 */

/**
 * @apiVersion 1.0.0
 * @apiGroup 朋友圈
 * @api {GET} api/moment/list 朋友圈列表
 * @apiName api/moment/list
 * @apiExample {js} axios 例子:
 *  axios.get('http://39.105.38.34:8080/api/moment/list', {
 *    params: {
 *      size: 10,
 *      page: 1,
 *      userid: 2,
 *    }
 *  });
 * @apiHeader {String} authorization 用户登录或注册成功时返回的 token
 * @apiParam {Number} [userid] 传了此参数，只获取某一个用户的朋友圈
 * @apiParam {Number} [page=1] 分页的页数
 * @apiParam {Number} [size=10] 每页的条数
 * @apiSuccess (请求成功) {Array} momentlist 朋友圈列表
 * @apiuse  ErrorResponse
 */

module.exports = async ctx => {
  var token = ctx.headers.authorization;
  var params = ctx.query;
  var user = await door(token);
  var sql = ['select * from moments where status = 1'];
  var values = [];
  var page = params.page ? params.page : 1;
  var size = params.size ? params.size : 10;
  var end = page * size;

  // 传入了 userid 时只获取该用户的朋友圈
  if (params.userid) {
    sql.push('and userid = ?');
    values.push(Number(params.userid));
  }

  sql.push('order by id desc limit ?, ?');
  values.push(end - size);
  values.push(end);

  var momentlist = await query(sql.join(' '), values);
  var momentlist = momentlist.map(item => {
    item.images = JSON.parse(item.images);
    return item;
  });
  var userids = momentlist.map(moment => moment.userid);
  var userlist = momentlist.length ? await query('select * from user where id in (?)', [userids]) : [];

  momentlist.forEach(moment => {
    userlist.forEach(user => {
      if (moment.userid === user.id) {
        moment.user = user;
      }
    })
  })

  ctx.body = ok({ momentlist });
}